//
//  AccountViewController.m
//  Village
//
//  Created by longrise on 2017/9/7.
//  Copyright © 2017年 程虎. All rights reserved.
//

#import "AccountViewController.h"
#import "AccountTableViewCell.h"
#import "AccountView.h"
#import "PickerChoiceView.h"//自定义选择器
#import "PasswordViewController.h"
#import "CertificateViewController.h"
#import "NicknameViewController.h"//昵称
#import "RevampPhoneViewController.h"
#import "TZPhotoScrollView.h"
#import "SettingHttpTools.h"
#import "PostedTools.h"

@interface AccountViewController ()<UITableViewDelegate,UITableViewDataSource,TFPickerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIAlertViewDelegate>
{
    NSInteger selectIndex;
}
@property (nonatomic , strong) UITableView *mytableview;
@property (nonatomic , strong) TZPhotoScrollView *headview;
@property (nonatomic , strong) AccountTableViewCell *cell;
@property (nonatomic ,strong) AccountView *header;
@property (nonatomic , strong) NSMutableArray *nameary;
@property (nonatomic, assign) BOOL systemEditing;
@property (nonatomic,strong)NSMutableArray *mutArray;
@property (nonatomic,strong)NSMutableArray *minetArray;
@property (nonatomic, copy) LongriseRouterBlock routerBlock;
@end

@implementation AccountViewController

- (void)setParams:(id)obj block:(LongriseRouterBlock)block
{
    self.routerBlock = block;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    if (_mytableview){
        [_mytableview reloadData];
    }
//    [self getdata];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"账号管理";
    [self BuildView];
    [self setdata];
    
    // Do any additional setup after loading the view.
}
//- (void)getdata{
//    NSMutableDictionary *bean = [NSMutableDictionary dictionary];
//    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//    [dict setObject:@"d92c6bf0c38a4842a13b17a0def673ec" forKey:@"id"];
//    [bean setValue:dict forKey:@"entitybean"];
//    [NetRequestClass Post:getUserInfoURL Parameters:bean success:^(id result) {
//        [MBProgressHUD hideHUDForView:self.navigationController.view];
//        [MBProgressHUD showSuccess:result[@"message"] toView:self.navigationController.view Completion:nil];
//        _minetArray = [NSMutableArray array];
//        for (int i = 0;i < _mutArray.count ; i ++){
//            if (result[@"data"][_mutArray[i]] == nil){
//                 [_minetArray addObject:@"暂未设置"];
//            }else{
//                 [_minetArray addObject:result[@"data"][_mutArray[i]]];
//            }
//        }
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [_mytableview reloadData];
//        });
//        LSLog(@"msg -----  %@",_minetArray);
//    } failure:^(id valueCode, id error) {
//        [MBProgressHUD hideHUDForView:self.navigationController.view];
//        [MBProgressHUD showError:error toView:self.navigationController.view];
//    }];
//}
- (void)BuildView{
    _mytableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, KDeviceHeight) style:UITableViewStylePlain];
    _mytableview.backgroundColor = kBackgroundColor;
    _mytableview.dataSource = self;
    _mytableview.delegate = self;
    [self.view addSubview:_mytableview];
    UIView *footview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, 100)];
    footview.backgroundColor = kBackgroundColor;
    _mytableview.tableFooterView = footview;
}

- (void)setdata{
   _nameary =[[NSMutableArray alloc] initWithObjects:@"头像",@"昵称",@"性别",@"生日",@"手机号",@"修改密码",@"证件信息",@"职位",@"任职单位" ,nil];
}
#pragma mark - 数据源方法
// 返回多少组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
// 返回行数
- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0){
        return 7;
    }else if(section == 1){
        return 2;
    }else if (section == 2){
        return 1;
    }
    return 0;
}
// 设置cell
- (UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    
    static NSString *cellID = @"id";
    AccountTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil)
    {
            cell = [[AccountTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            cell.backgroundColor = [UIColor whiteColor];
    }
    if (indexPath.section == 0){
        cell.leftlable.text = _nameary[indexPath.row];
        if (indexPath.row == 0){
            [cell.headview addSubview:self.headview];
            cell.rightlable.hidden = YES;
            cell.conterlable.hidden = YES;
        }else if(indexPath.row == 1){
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
            cell.headview.hidden = YES;
             cell.conterlable.hidden = YES;
              cell.rightlable.text =  [Globle getInstance].account.nickname;
            NSLog(@"%@---------------------------------- [Globle getInstance].account.nickname", [Globle getInstance].account.ID);
        }else if (indexPath.row == 2){
            NSString *str =  [Globle getInstance].account.sex;
            if ([str isEqualToString:@"1"]){
                  cell.rightlable.text = @"男";
            }else if([str isEqualToString:@"2"]){
                 cell.rightlable.text = @"女";
            }else{
                 cell.rightlable.text = @"";
            }
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
               cell.headview.hidden = YES;
            cell.conterlable.hidden = YES;
        }else if (indexPath.row == 3){
            
            if ([Globle getInstance].account.birthday == nil){
                cell.rightlable.text = [Globle getInstance].account.birthday;
            }else{
                NSString *str = [Globle getInstance].account.birthday;
                str = [str substringToIndex:10];//截取掉下标7之后的字符串
                cell.rightlable.text = str;
            }
            
         
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
            cell.headview.hidden = YES;
            cell.conterlable.hidden = YES;
        }else if (indexPath.row == 4){
//            NSString *str = [Tools replaceWithMobileNO:[Globle getInstance].account.phone number:3 numbei:4 change:@"****"];
//            cell.rightlable.text = str;
            cell.rightlable.text = [Globle getInstance].account.phone;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
            cell.headview.hidden = YES;
            cell.conterlable.hidden = YES;
        }else if (indexPath.row == 5){
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
            cell.headview.hidden = YES;
            cell.rightlable.hidden = YES;
            cell.conterlable.hidden = YES;
        }else{
//            if ([Globle getInstance].account.username == nil){
//                cell.rightlable.text = [Globle getInstance].account.username;
//            }else{
////                NSString *str = [Globle getInstance].account.username;
////                str = [str stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:@"*"];
////                cell.rightlable.text = str;
//
//            }
            cell.rightlable.text = [Globle getInstance].account.username;
            
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
        cell.headview.hidden = YES;
        cell.conterlable.hidden = YES;
        }
    }else if (indexPath.section == 2){
        cell.headview.hidden = YES;
        cell.rightlable.hidden = YES;
        cell.leftlable.hidden = YES;
    }else{
         cell.leftlable.text = _nameary[indexPath.row+7];
         cell.headview.hidden = YES;
         cell.conterlable.hidden = YES;
        switch (indexPath.row){
            case 1:
            {
                cell.rightlable.text = [Globle getInstance].account.position;
                break;
            }
            case 2:
            {
                cell.rightlable.text = [Globle getInstance].account.jobunit;
                break;
            }
        }
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];//cell点击之后没有视觉效果
    return cell;
}
#pragma mark - 代理方法
//设置行高
- (CGFloat)tableView:(nonnull UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    if (indexPath.section == 0){
        switch (indexPath.row){
            case 0:
            {
                return 90;
                break;
            }
        }
    }
    return 50;
}
// 添加每组的组头
- (UIView *)tableView:(nonnull UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, 10)];
    view.backgroundColor = kBackgroundColor;
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0){
        return 10;
    }else{
        return 10;
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}
// 返回每组的组尾
- (UIView *)tableView:(nonnull UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
// 选中某行cell时会调用
- (void)tableView:(nonnull UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    static NSString *cellID = @"id";
    AccountTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    PickerChoiceView *picker = [[PickerChoiceView alloc]initWithFrame:CGRectMake(0, 0, kDeviceWidth, KDeviceHeight
    )];
    picker.delegate = self;
    NSLog(@"选中didSelectRowAtIndexPath row = %ld", indexPath.row);
    if (indexPath.section == 0)
    {
        if (indexPath.row == 1){
            id obj = [LongriseRouter openURL:@"NicknameViewController"];
            if([LongriseRouter isImplLongriseRouterDelegaterWithObject:obj])
            {
                id<LongriseRouterDelegater> delegater = obj;
                if(delegater)
                {
                    //进行传值，传入统一的block以供B进行回调
                    [delegater setParams:@"1" block:^(id obj) {
                        NSLog(@"回调数据：%@",obj);
                    }];
                }
            }
            if (obj && [obj isKindOfClass:[UIViewController class]]) {
                UIViewController *VC = obj;
                VC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:VC animated:YES];
            }
        }
        if (indexPath.row == 2){
            selectIndex = 1;
            picker.arrayType = GenderArray;
            picker.selectStr  = cell.rightlable.text;
             [self.view addSubview:picker];//添加控制器
        }
        if (indexPath.row == 3){
            selectIndex = 2;
            picker.arrayType = DeteArray;
            picker.selectStr  = cell.rightlable.text;
            [self.view addSubview:picker];//添加控制器
        }
        if (indexPath.row == 4){
            id obj = [LongriseRouter openURL:@"RevampPhoneViewController"];
            if([LongriseRouter isImplLongriseRouterDelegaterWithObject:obj])
            {
                id<LongriseRouterDelegater> delegater = obj;
                if(delegater)
                {
                    //进行传值，传入统一的block以供B进行回调
                    [delegater setParams:@"1" block:^(id obj) {
                        NSLog(@"回调数据：%@",obj);
                    }];
                }
            }
            if (obj && [obj isKindOfClass:[UIViewController class]]) {
                UIViewController *VC = obj;
                VC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:VC animated:YES];
            }
        }
        if (indexPath.row == 5){
            id obj = [LongriseRouter openURL:@"RevampPassViewController"];
            if([LongriseRouter isImplLongriseRouterDelegaterWithObject:obj])
            {
                id<LongriseRouterDelegater> delegater = obj;
                if(delegater)
                {
                    //进行传值，传入统一的block以供B进行回调
                    [delegater setParams:@"1" block:^(id obj) {
                        NSLog(@"回调数据：%@",obj);
                    }];
                }
            }
            if (obj && [obj isKindOfClass:[UIViewController class]]) {
                UIViewController *VC = obj;
                VC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:VC animated:YES];
            }
        }else if(indexPath.row == 6){
            NSString *str = nil;
            
            if ([Globle getInstance].account.username == nil){
                str = @"1";
            }
            else{
                str = @"2";
            }
            [Tools ToNextName:@"CertificateViewController" Params:str CurrentVC:self Completion:^(id obj) {
            }];
        }
    }else if (indexPath.section == 1){
        
        
    }else{
        LRAlertView *alert = [[LRAlertView alloc] initWithAlertTitle:@"提示" Message:@"您确定要退出账号吗？" ButtonTitle:@"确定" OtherTitle:@"取消"];
        [alert showAlert];
        alert.btnClickBlock = ^(NSInteger index) {
            if (index == 0) {
                [[Globle getInstance] cleanAllObject];
                if (self.routerBlock) {
                    self.routerBlock(nil);
                }
                [_mytableview reloadData];
                [[NSNotificationCenter  defaultCenter] postNotificationName:RefreshLoginInfo object:nil];
                [self.navigationController popViewControllerAnimated:YES];
            }
        };
        
    }
}

- (void)PickerSelectorIndixString:(NSString *)str{
    NSMutableDictionary *bean = [NSMutableDictionary dictionary];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [bean setValue:dict forKey:@"entitybean"];
    [dict setObject:[Globle getInstance].account.userid.length > 0 ? [Globle getInstance].account.userid : @"" forKey:@"id"];
    if (selectIndex == 1){
        if ([str isEqualToString:@"男"]){
            str = @"1";
        }else{
            str = @"2";
        }
          [dict setObject:str forKey:@"sex"];
    }else{
          [dict setObject:str forKey:@"birthday"];
    }
    WeakSelf(weakSelf);
    [NetRequestClass Post:UpdateUserInfoURL Parameters:bean success:^(id result) {
        [MBProgressHUD hideHUDForView:weakSelf.navigationController.view];
        [MBProgressHUD showSuccess:@"上传成功！" toView:weakSelf.navigationController.view Completion:^{
        }];
         [[Globle getInstance] saveAccountInfo:result[@"data"]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [_mytableview reloadData];
        });
    } failure:^(id valueCode, id error) {
        [MBProgressHUD hideHUDForView:weakSelf.navigationController.view];
    }];
    
}

#pragma mark - 头像
- (TZPhotoScrollView *)headview
{
    if (_headview == nil) {
        self.headview = [[TZPhotoScrollView alloc] initWithFrame:CGRectMake(0, 0, 70, 70) ShowVC:self];
        self.headview.maxCountTF = 1;
        self.headview.columnNumberTF = 1;
        self.headview.isShowCell = YES;
        self.headview.allowCrop = YES;
        self.headview.needCircleCrop = YES;
        WeakSelf(weakSelf);
        self.headview.photoScrollBlcok = ^(NSArray *array) {
            [weakSelf uploadImage:array];
        };
    }
    return _headview;
}

#pragma mark - 上传头像
- (void)uploadImage:(NSArray *)array
{
    //=================基于LEAP的文件上传操作=================
    WeakSelf(weakSelf);
    [MBProgressHUD showMessage:@"正在加载..." toView:self.navigationController.view];
    [PostedTools UploadImgsWithIMGArys:array Success:^(NSArray *valueAry) {
        
        [weakSelf uploadheadImg:valueAry];
    } failure:^(NSString *error) {
        [MBProgressHUD hideHUDForView:self.navigationController.view];
        [MBProgressHUD showError:error toView:self.navigationController.view Completion:^{
            [JCAlertView showOneButtonWithTitle:@"取消" Message:error ButtonType:JCAlertViewButtonTypeCommonly ButtonTitle:@"确定" Click:^{
                [weakSelf uploadImage:array];
            }];
        }];
    }];
}

- (void)uploadheadImg:(NSArray *)arrays
{
    WeakSelf(weakSelf);
    [SettingHttpTools uploadUserIconWithImgAry:arrays Success:^(NSDictionary *valueDict) {
        [MBProgressHUD hideHUDForView:self.navigationController.view];
        [MBProgressHUD showSuccess:@"上传成功！" toView:weakSelf.navigationController.view Completion:^{
        }];
        [[Globle getInstance] saveAccountInfo:valueDict];
        [[NSNotificationCenter  defaultCenter] postNotificationName:RefreshLoginInfo object:nil];
    } failure:^(NSString *error) {
        [MBProgressHUD hideHUDForView:self.navigationController.view];
        [MBProgressHUD showError:error toView:self.navigationController.view];
    }];
}
@end
